package cn.edu.ecut.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class ConfigurationServlet implements Servlet {

    private ServletConfig sc ;

    @Override
    public void init( ServletConfig config ) throws ServletException {
        // 容器通过init方法的参数为servlet实例传递信息
        this.sc = config ;
    }

    @Override
    public void service(ServletRequest req , ServletResponse resp )
            throws ServletException, IOException {

        resp.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = resp.getWriter();

        // 所有的初始化参数都是针对Servlet实例的

        Enumeration<String> initParamNames = sc.getInitParameterNames(); // 获取所有的初始化参数名称组成的Enumeration对象
        while( initParamNames.hasMoreElements() ) { // 判断是否有更多元素需要处理
            String paramName = initParamNames.nextElement(); // 获取下一个元素
            String paramValue = sc.getInitParameter( paramName ); // 根据 初始化参数名称 获取 取值

            System.out.println( paramName + " : " + paramValue ); // 输出到控制台

            out.println( "<div>" );
            out.println(  paramName + " : " + paramValue );
            out.println( "</div>" );
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public ServletConfig getServletConfig() {
        return this.sc;
    }

    @Override
    public String getServletInfo() {
        String info = sc.getServletName() + " : " + this ;
        return  info ;
    }

}
